<?php


namespace app\admin\controller\User;



use app\admin\controller\BaseController;
use app\admin\model\User\UserLevelModel;
use app\Utils\ImageUtil;
use app\Utils\Util;
use Exception;
use think\facade\Db;
use think\Request;

class UserLevel extends BaseController
{

    /**
     * 分页查询
     * @param Request $request
     * @return array
     */
    public function getUserLevelList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = $param['page'];
        $limit = $param['limit'];
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        if (empty($page)) {
            $page = 1;
        }
        if (empty($limit)) {
            $limit = 10;
        }
        if (!empty($is_show)) {
            if ($is_show == 1) {
                array_push($where, ['is_show', '=', 0]);
            }
            if ($is_show == 2) {
                array_push($where, ['is_show', '=', 1]);
            }
        }
        $list = UserLevelModel::getUserLevelListWhere($page, $limit, $where);
        $count = UserLevelModel::getUserLevelCountWhere($where);
        foreach ($list as &$item){
            $item['icon'] = ImageUtil::i()->replaceUrl($item['icon']);
            $item['remarks'] = json_decode($item['remarks'],true);
            $item['merchant_ratio'] = bcmul($item['merchant_ratio'],100,0);
            if(!empty($item['sales_setting'])){
                $sales_setting = json_decode($item['sales_setting'],true);
                $item['level'] = $sales_setting['level'];
                $item['level_sales0'] = $sales_setting['level_sales0'];
                $item['level_sales1'] = $sales_setting['level_sales1'];
                $item['level_sales2'] = $sales_setting['level_sales2'];
            }else{
                $item['level'] = 0;
                $item['level_sales0'] = 0;
                $item['level_sales1'] = 0;
                $item['level_sales2'] = 0;
            }
        }

        return Util::returnPageJson(self::CODE_DATA, $count, $list, "");

    }


    /**
     * 添加
     * @param Request $request
     * @return array
     */
    public function addUserLevel(Request $request)
    {
        $param = $request->param();

        $sales_setting = [
            'level'=>$param['level'],
            'level_sales0'=>$param['level_sales0'],
            'level_sales1'=>$param['level_sales1'],
            'level_sales2'=>$param['level_sales2'],
        ];

        $data = [
            'level_name' => !empty($param['level_name']) ? $param['level_name'] : "",
            'price'  => !empty($param['price']) ? $param['price'] : 0,
            'cost_price'  => !empty($param['cost_price']) ? $param['cost_price'] : 0,
            'day'    => !empty($param['day']) ? $param['day'] : 0,
            'study_money'   => !empty($param['study_money']) ? $param['study_money'] : 0,
            'type'          => !empty($param['type']) ? $param['type'] : 0,
            'sort' => !empty($param['sort']) ? $param['sort'] : 0,
            'merchant_ratio' => bcdiv($param['merchant_ratio'],100,2),
            'is_sales'       => !empty($param['is_sales']) ? $param['is_sales'] : 0,
            'sales_setting'  => json_encode($sales_setting),
            'up_time' => date("Y-m-d H:i:s",time()),
            'add_time' => date("Y-m-d H:i:s",time())
        ];

        $equity = [];
        if(($param['equity_title'] && ($param['equity_remarks']))){
            foreach ($param['equity_title'] as $k=>$item){
                $array['equity_title']   = !empty($param['equity_title'][$k]) ? $param['equity_title'][$k] : "";
                $array['equity_remarks'] = !empty($param['equity_remarks'][$k]) ? $param['equity_remarks'][$k] : "";
                array_push($equity,$array);
            }
        }
        $data['remarks'] = json_encode($equity);

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/member/level/";
            $url = ImageUtil::i()->upload($file, $path);
        }

        if (!empty($url)) {
            $data['icon'] = $url;
        }
        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $data['is_show'] = 1;
        }else{
            $data['is_show'] = 0;
        }

        $id = UserLevelModel::addUserLevel($data);
        if ($id) {
            return Util::returnJson(self::CODE_SUCCESS, $id, "添加成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "添加失败");
        }
    }

    /**
     * 更新
     * @param Request $request
     * @return array
     */
    public function editUserLevel(Request $request)
    {
        $param = $request->param();

        $sales_setting = [
            'level'=>$param['level'],
            'level_sales0'=>$param['level_sales0'],
            'level_sales1'=>$param['level_sales1'],
            'level_sales2'=>$param['level_sales2'],
        ];

        $save = [
            'level_name' => !empty($param['level_name']) ? $param['level_name'] : "",
            'price'  => !empty($param['price']) ? $param['price'] : 0,
            'cost_price'  => !empty($param['cost_price']) ? $param['cost_price'] : 0,
            'day'    => !empty($param['day']) ? $param['day'] : 0,
            'study_money'   => !empty($param['study_money']) ? $param['study_money'] : 0,
            'type'          => !empty($param['type']) ? $param['type'] : 0,
            'sort' => !empty($param['sort']) ? $param['sort'] : 0,
            'merchant_ratio' => bcdiv($param['merchant_ratio'],100,2),
            'is_sales'       => !empty($param['is_sales']) ? $param['is_sales'] : 0,
            'sales_setting'  => json_encode($sales_setting),
            'up_time' => date("Y-m-d H:i:s",time())
        ];

        $equity = [];
        if(($param['equity_title'] && ($param['equity_remarks']))){
            foreach ($param['equity_title'] as $k=>$item){
                $array['equity_title']   = !empty($param['equity_title'][$k]) ? $param['equity_title'][$k] : "";
                $array['equity_remarks'] = !empty($param['equity_remarks'][$k]) ? $param['equity_remarks'][$k] : "";
                array_push($equity,$array);
            }
        }
        $save['remarks'] = json_encode($equity);

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/member/level/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        if (!empty($url)) {
            $save['icon'] = $url;
        }

        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $save['is_show'] = 1;
        }else{
            $save['is_show'] = 0;
        }

        $flag = UserLevelModel::updateUserLevelWhere([['id', '=', $param['id']]], $save);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
        }
    }

    /**
     * 更新状态
     * @param Request $request
     * @return array
     */
    public function editUserLevelType(Request $request)
    {
        $param = $request->param();
        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $save['is_show'] = 1;
        }else{
            $save['is_show'] = 0;
        }

        $flag = UserLevelModel::updateUserLevelWhere([['id', '=', $param['id']]], $save);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return array
     */
    public function delUserLevel(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        //开启事务
        Db::startTrans();
        try {
            //中间逻辑代码
            $flag = UserLevelModel::delUserLevelWhere([['id', '=', $id]]);
            if ($flag) {
                DB::commit();
                return Util::returnJson(self::CODE_SUCCESS, null, "删除成功");
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "删除失败");
            }
        } catch (Exception $e) {
            //接收异常处理并回滚
            //回滚事务
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, $e, "删除失败");
        }
    }

}
